package com.zhangxin.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * 自定义一个助手类（handler)
 */
public class CustomerHandler extends SimpleChannelInboundHandler<HttpObject> {


    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject)
            throws Exception {
        // 获取channel
        Channel channel = channelHandlerContext.channel();

        System.out.println("[远程请求的ip地址]" + channel.remoteAddress());

        // 封装返回的数据
        ByteBuf content = Unpooled.copiedBuffer("hello netty ~", CharsetUtil.UTF_8);

        // 构造一个返回的response
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                content);

        // 为响应增加数据类型和长度
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

        // 将响应刷新到客户端上面去
        channelHandlerContext.writeAndFlush(response);
    }
}
